package com.nowcoder.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.mapper.UserMapper;
import com.nowcoder.community.service.IUserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ChenJH
 * @since 2022-12-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, CommunityConstant {

    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;


    @Autowired
    private RedisTemplate template;
    @Autowired
    LoginTicketServiceImpl loginTicketService;

    /**
     * 重写获取方法 从缓存中获取
     * @param id
     * @return
     */
    @Override
    public User getById(Serializable id) {
        User user = getCache( id);
        if (user == null){
            user = initCache( id);
        }
        return user;
    }

    @Override
    public Map<String, Object> register(User user) {
        HashMap<String, Object> map = new HashMap<>();
//
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
            return map;
        }
//        验证账号
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User one = getOne(wrapper);
        if (one != null) {
            map.put("usernameMsg", "该账号已存在");
            return map;
        }

        wrapper.clear();
        wrapper.eq(User::getEmail, user.getEmail());
        one = getOne(wrapper);
        if (one != null) {
            map.put("emailMsg", "该邮箱已存在");
            return map;
        }
//注册
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(LocalDateTime.now());
        save(user);
//激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        //http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }

    /**
     * @param userId
     * @param code   是激活码
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, userId);
        User user = getOne(wrapper);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId);
            updateWrapper.set(User::getStatus, 1);
            update(updateWrapper);

//            激活后 也算是修改了用户 需要删除缓存
            clearCache(String.valueOf(userId));

            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = getOne(wrapper);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在");
            return map;
        }
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活");
            return map;
        }
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确");
            return map;
        }
        LoginTicket loginTicket = new LoginTicket();
//        这里是直接添加秒数 就不用*1000  因为那是毫秒
        loginTicket.setUserId(user.getId()).setTicket(CommunityUtil.generateUUID())
                .setStatus(0).setExpired(LocalDateTime.now().plusSeconds(expiredSeconds));

//        loginTicketService.save(loginTicket);
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        template.opsForValue().set(redisKey, loginTicket);


        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
//        LambdaUpdateWrapper<LoginTicket> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(LoginTicket::getTicket, ticket);
//        wrapper.set(LoginTicket::getStatus, 1);
//        loginTicketService.update(wrapper);

        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) template.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        template.opsForValue().set(redisKey, loginTicket);

    }

    @Override
    public LoginTicket findLoginTicket(String ticket) {
//        LambdaQueryWrapper<LoginTicket> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(LoginTicket::getTicket, ticket);
//        return loginTicketService.getOne(wrapper);

        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) template.opsForValue().get(redisKey);
    }

    @Override
    public boolean updateHeader(int userId, String headerUrl) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId, userId);
        wrapper.set(User::getHeaderUrl, headerUrl);
        boolean update = update(wrapper);

//     清理缓存
        clearCache( String.valueOf(userId));

        return update;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = getById(userId);
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1:
                        return AUTHORITY_ADMIN;
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

    /**
     * 1----优先从缓存中取值
     * @param userId
     * @return
     */
    private User getCache(Serializable userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) template.opsForValue().get(redisKey);
    }

    /**
     * 2-----取不到时 初始化缓存数据
     * @param userId
     * @return
     */
    private User initCache(Serializable userId){
        User user = this.getBaseMapper().selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
//        保存时间设为1h
//        *****必须设置时间单位不然报错
        template.opsForValue().set(redisKey,user,3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 3----数据变化时 清除缓存数据
     * @param userId
     */
    private void clearCache(Serializable userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        template.delete(redisKey);
    }


}
